﻿using UnityEngine.EventSystems;

namespace UnityEngine.UI
{
    public class UIListener : MonoBehaviour
    {
        public delegate void UIVoidEventHandler();
        public delegate void UIPointerEventHandler(PointerEventData eventData);

        public event UIVoidEventHandler OnVoidTrigger;
        public event UIPointerEventHandler OnPointerTrigger;

        protected void NotifyTrigger(PointerEventData eventData)
        {
            if (OnVoidTrigger != null)
            {
                OnVoidTrigger();
            }

            if (OnPointerTrigger != null)
            {
                OnPointerTrigger(eventData);
            }
        }

        /// <summary>
        /// 克隆另一个监听器的事件
        /// </summary>
        /// <param name="l"></param>
        public void CloneFrom(UIListener l)
        {
            if (l == null)
                return;

            OnVoidTrigger += l.OnVoidTrigger;
            OnPointerTrigger += l.OnPointerTrigger;
        }

        /// <summary>
        /// 添加监听
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="comp"></param>
        /// <param name="callback"></param>
        public static void AddListener<T>(Component comp, UIVoidEventHandler callback) where T : UIListener, IEventSystemHandler
        {
            T listener = comp.gameObject.GetComponent<T>();
            if (listener == null)
            {
                listener = comp.gameObject.AddComponent<T>();
            }
            listener.OnVoidTrigger += callback;
        }

        /// <summary>
        /// 添加监听
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="comp"></param>
        /// <param name="callback"></param>
        public static void AddListener<T>(Component comp, UIPointerEventHandler callback) where T : UIListener, IEventSystemHandler
        {
            T listener = comp.gameObject.GetComponent<T>();
            if (listener == null)
            {
                listener = comp.gameObject.AddComponent<T>();
            }
            listener.OnPointerTrigger += callback;
        }
    }
}